package com.crazymakercircle.mutithread.basic.use;

import lombok.extern.slf4j.Slf4j;

import static com.crazymakercircle.util.ThreadUtil.getCurThread;
import static com.crazymakercircle.util.ThreadUtil.sleepMilliSeconds;

/**
 * Created by 尼恩@疯狂创客圈.
 */
@Slf4j
public class DaemonDemo {
    public static final int SLEEP_GAP = 500; //每一轮的睡眠时长
    public static final int MAX_TURN = 4; //用户线程执行轮次

    public static void main(String[] args) throws InterruptedException {

        // 只要尚存一个用户线程没有结束，守护线程就能执行自己工作
        // 只有当最后一个用户线程结束，守护线程随着JVM一同结束工作
        Thread daemonThread = new DaemonThread();
        daemonThread.setDaemon(true);
        daemonThread.start();

        Thread userThread = new Thread(() -> {
            log.info(">>用户线程开始.");
            for (int i = 1; i <= MAX_TURN; i++) {
                log.info(">>轮次：" + i + " -守护状态为:" + getCurThread().isDaemon());
                sleepMilliSeconds(SLEEP_GAP);
            }
            log.info(">>用户线程结束.");
        }, "userThread");
        userThread.start();
        //主线程合入userThread，等待userThread执行完成
//        userThread.join();
        log.info(" main线程是不是守护线程:" + getCurThread().isDaemon());

        log.info(" main线程运行结束.");
    }

    //守护线程实现类
    static class DaemonThread extends Thread {

        public DaemonThread() {
            super("daemonThread");
        }

        public void run() {
            log.info("--daemon线程开始.");

            // 死循环
            for (int i = 1; ; i++) {
                log.info("--轮次：" + i + "--守护状态为:" + isDaemon());
                // 线程睡眠一会
                sleepMilliSeconds(SLEEP_GAP);
            }
        }
    }
}